package sbc.jms;

import java.util.Date;

import javax.ejb.ActivationConfigProperty;
import javax.ejb.EJB;
import javax.ejb.MessageDriven;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.ObjectMessage;

import org.jboss.logging.Logger;

import sbc.ejb3.Platine;
import sbc.ejb3.dao.PlatineRemote;
import sbc.ms.Producer;

@MessageDriven(activationConfig =
{     
      @ActivationConfigProperty(propertyName="destinationType", propertyValue="javax.jms.Queue"),
      @ActivationConfigProperty(propertyName="destination", propertyValue="queue/logisticQueue"),
      @ActivationConfigProperty(propertyName="DLQMaxResent", propertyValue="2")
})
public class LogisticListener implements MessageListener {

	static Logger log = Logger.getLogger(LogisticListener.class);
	
	private static final String MS_URL = "http://localhost:8081/xvsm-0.8.3/xvsm";
	
    @EJB private PlatineRemote platineDAO;	
	

	public LogisticListener(){
		log.debug("LogisticListener MDB constructed");
	}	

    public void onMessage(Message m) {
		log.info("message received");
		
		try {
			/*
			 * read message
			 */
			ObjectMessage message = (ObjectMessage)m;
			Object object = message.getObject();
			log.info("object: " + object);
			
			if (object instanceof Platine) {
				Platine platine = (Platine) object;
        		
        		/*
        		 * declare Platine IstAusgeliefert 
        		 */
        		platine.setAusgeliefertAm(new Date());
        		platineDAO.merge(platine);
				
				/*
				 * forward Platine to Mozart Space
				 */
				sbc.model.Platine msPlatine= new sbc.model.Platine();
        		msPlatine.setMyId(platine.toString());
        		
        		Producer p = new Producer(MS_URL, msPlatine);
        		p.start();
			}
			
		}
		catch(Exception e) {
	        log.error("error during message forwarding: " + e);
		}		
    }
}
